---
title: Object-Oriented Programming Basics
---

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. C++ is a multi-paradigm language with strong support for OOP, while JavaScript uses a prototype-based object model.

## Class and Object Definition

In C++, a **class** is a blueprint for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions). An **object** is an instance of a class.

<UniversalEditor title="Class and Object Definition Comparison" compare={true}>
```javascript !! js
// JavaScript: Object Literal and Constructor Function
// Object Literal
const car1 = {
  brand: "Toyota",
  model: "Camry",
  start: function() {
    console.log(`${this.brand} ${this.model} started.`);
  }
};
car1.start();

// Constructor Function
function Car(brand, model) {
  this.brand = brand;
  this.model = model;
  this.start = function() {
    console.log(`${this.brand} ${this.model} started.`);
  };
}
const car2 = new Car("Honda", "Civic");
car2.start();

// ES6 Class Syntax (syntactic sugar over prototypes)
class Vehicle {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }
  start() {
    console.log(`${this.brand} ${this.model} started.`);
  }
}
const car3 = new Vehicle("Ford", "Focus");
car3.start();
```

```cpp !! cpp
// C++: Class and Object Definition
#include <iostream>
#include <string>

class Car { // Class definition
public: // Access specifier
  std::string brand; // Member variables
  std::string model;

  void start() { // Member function
    // std::cout << brand << " " << model << " started." << std::endl;
  }
};

int main() {
  Car car1; // Create an object (instance) of the Car class
  car1.brand = "Toyota";
  car1.model = "Camry";
  car1.start();

  Car car2; // Another object
  car2.brand = "Honda";
  car2.model = "Civic";
  car2.start();

  return 0;
}
```
</UniversalEditor>

## Constructors and Destructors

**Constructors** are special member functions that are automatically called when an object is created. They are used to initialize the object's state.

**Destructors** are special member functions that are automatically called when an object is destroyed (goes out of scope or is `delete`d). They are used to clean up resources (e.g., deallocate dynamically allocated memory).

<UniversalEditor title="Constructor and Destructor Comparison" compare={true}>
```javascript !! js
// JavaScript: Constructor Function and Class Constructor
function Person(name, age) {
  this.name = name;
  this.age = age;
  console.log(`${this.name} created.`);
}
const p1 = new Person("Alice", 30);
// No explicit destructor; garbage collector handles cleanup

class Animal {
  constructor(name) {
    this.name = name;
    console.log(`${this.name} (Animal) created.`);
  }
  // No explicit destructor
}
const a1 = new Animal("Leo");
```

```cpp !! cpp
// C++: Constructors and Destructors
#include <iostream>
#include <string>

class Person {
public:
  std::string name;
  int age;

  // Constructor
  Person(std::string n, int a) : name(n), age(a) {
    // std::cout << name << " (Person) created." << std::endl;
  }

  // Destructor
  ~Person() {
    // std::cout << name << " (Person) destroyed." << std::endl;
  }
};

int main() {
  Person p1("Alice", 30); // Constructor called
  // p1 goes out of scope here, destructor called automatically

  Person* p2 = new Person("Bob", 25); // Constructor called
  delete p2; // Destructor called explicitly

  return 0;
}
```
</UniversalEditor>

## Encapsulation and Access Control

**Encapsulation** is the bundling of data (member variables) and methods (member functions) that operate on the data into a single unit (class), and restricting direct access to some of the object's components. This is achieved using **access specifiers**:

*   `public`: Members are accessible from anywhere.
*   `private`: Members are only accessible from within the class itself.
*   `protected`: Members are accessible from within the class and by derived classes.

<UniversalEditor title="Encapsulation Comparison" compare={true}>
```javascript !! js
// JavaScript: Encapsulation (using closures or #private fields)
class BankAccount {
  #balance; // Private field (ES2019+)

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
      console.log(`Deposited: ${amount}. New balance: ${this.#balance}`);
    }
  }

  getBalance() {
    return this.#balance;
  }
}

const myAccount = new BankAccount(100);
myAccount.deposit(50);
// console.log(myAccount.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
console.log(myAccount.getBalance()); // 150
```

```cpp !! cpp
// C++: Encapsulation with Access Specifiers
#include <iostream>

class BankAccount {
private: // Private member variable
  double balance;

public: // Public member functions
  BankAccount(double initialBalance) : balance(initialBalance) {}

  void deposit(double amount) {
    if (amount > 0) {
      balance += amount;
      // std::cout << "Deposited: " << amount << ". New balance: " << balance << std::endl;
    }
  }

  double getBalance() const { // const indicates it doesn't modify object state
    return balance;
  }
};

int main() {
  BankAccount myAccount(100);
  myAccount.deposit(50);
  // myAccount.balance = 1000; // Error: 'balance' is private
  // std::cout << myAccount.getBalance() << std::endl; // 150
  return 0;
}
```
</UniversalEditor>

## Basic Inheritance

**Inheritance** is a mechanism where a new class (derived class or subclass) is created from an existing class (base class or superclass). The derived class inherits properties and behaviors from the base class, promoting code reuse.

<UniversalEditor title="Basic Inheritance Comparison" compare={true}>
```javascript !! js
// JavaScript: Class Inheritance
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // Call parent constructor
    this.breed = breed;
  }
  speak() {
    console.log(`${this.name} (${this.breed}) barks.`);
  }
}

const myDog = new Dog("Buddy", "Golden Retriever");
myDog.speak(); // Buddy (Golden Retriever) barks.
```

```cpp !! cpp
// C++: Basic Inheritance
#include <iostream>
#include <string>

class Animal { // Base class
public:
  std::string name;
  Animal(std::string n) : name(n) {}
  void speak() {
    // std::cout << name << " makes a sound." << std::endl;
  }
};

class Dog : public Animal { // Derived class, public inheritance
public:
  std::string breed;
  Dog(std::string n, std::string b) : Animal(n), breed(b) {} // Call base class constructor
  void speak() { // Override base class method
    // std::cout << name << " (" << breed << ") barks." << std::endl;
  }
};

int main() {
  Dog myDog("Buddy", "Golden Retriever");
  myDog.speak();
  return 0;
}
```
</UniversalEditor>

## Polymorphism Concept

**Polymorphism** (meaning "many forms") allows objects of different classes to be treated as objects of a common base class. In C++, polymorphism is primarily achieved through **virtual functions** and **pointers/references to base classes**.

<UniversalEditor title="Polymorphism Concept Comparison" compare={true}>
```javascript !! js
// JavaScript: Polymorphism (achieved naturally through dynamic typing and prototypes)
class Shape {
  draw() {
    console.log("Drawing a generic shape.");
  }
}

class Circle extends Shape {
  draw() {
    console.log("Drawing a circle.");
  }
}

class Rectangle extends Shape {
  draw() {
    console.log("Drawing a rectangle.");
  }
}

const shapes = [new Shape(), new Circle(), new Rectangle()];

shapes.forEach(shape => shape.draw());
// Output:
// Drawing a generic shape.
// Drawing a circle.
// Drawing a rectangle.
```

```cpp !! cpp
// C++: Polymorphism with Virtual Functions
#include <iostream>

class Shape { // Base class
public:
  virtual void draw() { // Virtual function
    // std::cout << "Drawing a generic shape." << std::endl;
  }
};

class Circle : public Shape { // Derived class
public:
  void draw() override { // Override keyword (C++11) for clarity
    // std::cout << "Drawing a circle." << std::endl;
  }
};

class Rectangle : public Shape { // Derived class
public:
  void draw() override {
    // std::cout << "Drawing a rectangle." << std::endl;
  }
};

int main() {
  Shape* s1 = new Shape();
  Shape* s2 = new Circle(); // Base class pointer pointing to derived class object
  Shape* s3 = new Rectangle();

  s1->draw(); // Calls Shape::draw()
  s2->draw(); // Calls Circle::draw() (polymorphic behavior)
  s3->draw(); // Calls Rectangle::draw() (polymorphic behavior)

  delete s1; delete s2; delete s3;
  return 0;
}
```
</UniversalEditor>

## Comparison with JavaScript Prototype Chain

JavaScript's object model is prototype-based, not class-based in the traditional sense (though ES6 classes provide syntactic sugar). When you try to access a property or method on an object, JavaScript first looks for it directly on the object. If not found, it looks on the object's prototype, then on the prototype's prototype, and so on, forming a **prototype chain**.

**Key Differences:**
*   **Inheritance Model:** C++ uses classical inheritance (class-based), while JavaScript uses prototypal inheritance.
*   **Explicit vs. Implicit:** C++ inheritance is explicit with keywords like `class` and `public/private/protected`. JavaScript's prototypal inheritance is more implicit.
*   **Polymorphism:** C++ relies on virtual functions and base class pointers/references for runtime polymorphism. JavaScript achieves polymorphism naturally due to its dynamic nature and prototype chain.

## Virtual Function Mechanism

In C++, a **virtual function** is a member function that is declared within a base class and redefined (overridden) by a derived class. When you call a virtual function through a pointer or reference to the base class, the specific version of the function that is executed is determined at runtime based on the actual type of the object being pointed to or referenced. This is known as **dynamic dispatch** or **runtime polymorphism**.

*   **`virtual` keyword:** Declares a function as virtual in the base class.
*   **`override` keyword (C++11):** Optional, but good practice in derived classes to indicate that a function is intended to override a virtual function from a base class. Helps catch errors if the signature doesn't match.
*   **Virtual Table (vtable):** Compilers typically implement virtual functions using a virtual table, which is a lookup table of function pointers.

---

### Practice Questions:
1.  Explain the concepts of encapsulation and inheritance in C++. How do access specifiers (`public`, `private`, `protected`) relate to encapsulation?
2.  What is polymorphism in C++, and how is it achieved using virtual functions? Provide a simple C++ code example demonstrating runtime polymorphism.
3.  Compare and contrast C++'s class-based inheritance with JavaScript's prototype-based inheritance. What are the main differences in how they achieve object-oriented principles?

### Project Idea:
*   Design and implement a simple `Shape` hierarchy in C++ using inheritance and polymorphism. Create base class `Shape` with a virtual `calculateArea()` method. Derive `Circle` and `Rectangle` classes from `Shape`, each overriding `calculateArea()` to provide their specific implementation. Then, create an array of `Shape` pointers and demonstrate calling `calculateArea()` polymorphically for different shapes.
